import pyodbc as db, BaseFunction as BF
import 笔趣阁 as bqg, 搜搜小说网 as ss, 第二课堂 as xbqg
import MyClass as mc
import sys, time
import pymssql as ms


def Search(bk):
    bs = []
    bc1 = list(bqg.GetSearchResult(bk))
    bc2 = list(ss.GetSearchPageResultByName(bk))
    bs.append(bc1)
    bs.append(bc2)

    now = 0
    print('关键词：' + str(bk))
    for bc in bs:
        if bc.count == 0:
            return
        for b in bc:
            print("小说:" + str(now) + '/' + str(len(bc)) + "  " + b.name)
            # 过滤重复
            now += 1
            if BF.selectmssql('Select COUNT(BID) C From BooksInfo Where Name=%s and Author=%s' \
                    , (b.name, b.author), **BF.sqlparms)[0]['C'] > 0:
                continue
            BF.save2mysql("Insert into BooksInfo Values(%s,%s,%s,%s,%s,%s,%s)", \
                          [(b.name, b.type1, b.author, b.source, b.href, b.utime, 1)], **BF.sqlparms)
            b.ID = BF.selectmssql("Select BID From BooksInfo Where Name=%s and Author=%s", \
                                  (b.name, b.author), **BF.sqlparms)[0]['BID']
            # 获取当前小说目录
            link = b.href
            zjc = list(bqg.ZJIndex(link))
            zjc = bqg.GetBody(zjc)
            try:
                BF.Save(zjc, b.ID)
            except Exception as err:
                BF.save2mysql("Delete From BooksInfo Where Name=%s and Author=%s", \
                              [(b.name, b.author)], **BF.sqlparms)
                print(err)
            print("****************************************")


rows = BF.selectmssql('select search,ID from SearchRecord where State>0', (), **BF.sqlparms)
for row in rows:
    Search(row['search'])
    BF.save2mysql('Update SearchRecord Set State = 0 where ID=' + str(row['ID']), [], **BF.sqlparms)
else:
    print("没有需要爬取的")
